package com.example.controlstock1;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class FrmListado extends Activity {
	
	private ListView lstClientes;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_frm_listado);
		
		 lstClientes = (ListView)findViewById(R.id.LstStock);
		 
		 HttpClient httpClient = new DefaultHttpClient();
			
			HttpGet del = 
					new HttpGet("http://186.136.124.141/stock/service.stock.php");
			
			del.setHeader("content-type", "application/json");
			
			try
	        {			
	        	HttpResponse resp = httpClient.execute(del);
	        	String respStr = EntityUtils.toString(resp.getEntity());
	        	
	        	JSONObject jsObject = new JSONObject(respStr);
	        	
	        	JSONArray respJSON= jsObject.getJSONArray("stock");
	        	
	        	//JSONArray respJSON = new JSONArray(respStr);
	        	
	        	
	        	String[] stock = new String[respJSON.length()];
	        			
	        	for(int i=0; i<respJSON.length(); i++)
	        	{
	        		JSONObject obj = respJSON.getJSONObject(i);
	        		
		        	String codigo = obj.getString("codigo");
		        	//String descripcion = obj.getString("descripcion");
		        	int cantidad = obj.getInt("cantidad");
		        	String unidad = obj.getString("descripcion");
		        	
	        		stock[i] = "" + codigo + "-" + cantidad + "-" + unidad;
	        	}
	        	
	        	//Rellenamos la lista con los resultados
	        	ArrayAdapter<String> adaptador =
	        		    new ArrayAdapter<String>(FrmListado.this,
	        		        android.R.layout.simple_list_item_1, stock);
	        	

	        		 
	        	lstClientes.setAdapter(adaptador);
	        }
			catch(JSONException e){
     		System.out.print(e);
     	}
	        catch(Exception ex)
	        {
	        	Log.e("ServicioRest","Error!", ex);
	        }
		
		
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_frm_listado, menu);
		return true;
	}

}
